package com.wangwenjun.concurrency.chapter17;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class TaoBaoTest5 {


    public static void main(String[] args) throws InterruptedException {
        char[] cArray = "ABCDEFG".toCharArray();
        char[] nArray = "1234567".toCharArray();

        ReentrantLock lock = new ReentrantLock();
        Condition cCondition = lock.newCondition();
        Condition nCondition = lock.newCondition();

        /**
         * 0:数字输出
         * 1:字母输出
         */
        AtomicInteger flag = new AtomicInteger(1);

        new Thread(()->{
            lock.lock();
            try{
                for (char element: nArray) {
                    while (flag.get() != 0){
                        nCondition.await();
                    }
                    System.out.println(element);
                    flag.set(1);
                    cCondition.signal(); // 不会释放锁(需要和unlock配合)
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }).start();

        new Thread(()->{
            lock.lock();
            try{
                for (char element: cArray) {
                    while (flag.get() != 1){
                        cCondition.await();
                    }
                    System.out.println(element);
                    flag.set(0);
                    nCondition.signal(); // 不会释放锁
                }
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            } finally {
                lock.unlock();
            }
        }).start();

    }
}
